package com.sockety2;

import static java.lang.System.out;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;

public class ThrSocket2 extends Thread {
	public boolean run = true;
	private Socket incoming;
	private Server server;
	BehStd stdBeh = new BehStd();
	
	
	
	public ThrSocket2(Socket socket, Server server){
		this.server = server;
		this.incoming = socket;
	}
	
	
	
	@Override
	public void run() {
		if(incoming == null){return;}
		
		try{
            try{
                BufferedReader br = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                
                OutputStream outStream = incoming.getOutputStream();
                PrintWriter pw = new PrintWriter(outStream, true);
                pw.println(this.getName() + "|" + new Date());
                
                String line = null;
                
                while(true){
                	
                	try {
						
                		while(!br.ready() ){
                			if(!run){break;}
                			Thread.sleep(200);
                			//out.println(this.getName() + " sleep"  );
                		}
                		if(!run){break;}
                		line = br.readLine();
                		
					} catch (InterruptedException e) {
						out.println(this.getName() + " InterruptedException"  );
					}
                	
                	
                    out.println(line);
                    pw.println("ECHO: " + line);
                    if(line.trim().equals("-shd")){server.run = false;};
                    
                    Object result = stdBeh.todo(line.trim());
                    
                    if(result != null){
                    	if( result instanceof String){
                    		String strResult = (String)result;
                    		pw.println();
                    		pw.print(strResult);
                    	}
                    }
                    
                }
            }
            finally{
                incoming.close();
            }
        }
        catch(IOException e ){
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
	
	}
}
